from apps.merchant.item.baseViews import *
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import qrcode
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.http import FileResponse
from apps.merchant.sku.dao import SkuDao
import requests
from project.settings import os, BASE_DIR

class ItemViewForCSet(BaseItemViewSet):
    serializer_class = ItemForCListSerializer

    authentication_classes = []
    permission_classes = []
    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = ItemDao().findAllItemForC()
        if params.get('itemResource') == '0':
            _list = _list.filter(shop__types='0')
        elif params.get('itemResource') == '1':
            _list = _list.filter(shop__types='1')
        if params.get('routeName') == 'giftSection':
            _list = _list.filter(activity__id=31)
        if params.get('tags'):
            if params.get('tags') == '5':
                _list = _list.order_by('createTime')
        return _list

    @action(methods=['post'], detail=False, authentication_classes = [TokenAuthentication], permission_classes = [IsAuthenticated])
    def getItemById(self, request):
        params = getRequestParams(self.request)
        try:
            obj_id = params.get('obj_id')
            if not obj_id:
                return Response(response_message('obj_id参数必填'))
            obj = self.DAO_CLASS().findOneByObjId(obj_id)
            if not obj:
                return Response(response_message('商品不存在'))
            if obj.status != 1:
                return Response(response_message('商品已下架'))
            if obj.checkStatus != 'PASS':
                return Response(response_message('商品审核中'))
            model = ItemModelSerializer(obj, context={'request':request}).data
            res = {'selfSendIncomesLocked':0}
            if obj.shop.types == '0':
                res = countProfitFun({'sellingPrice': model.get('priceModel').get('sellingPrice'), 'costPrice': model.get('priceModel').get('costPrice'), 'activityId': obj.activity.id, 'scene': 'generay', 'payCount': 1})
            elif obj.shop.types == '1':
                res = countProfitForFranchiseeFun({'sellingPrice': model.get('priceModel').get('sellingPrice'), 'costPrice': model.get('priceModel').get('costPrice'), 'activityId': '', 'scene': 'shopItem'})
            model['incomesLockedsMessee'] = '预计获得补贴'
            model['incomesLockedsCount'] = str(res.get('selfSendIncomesLocked'))
        except VerifyException as e:
            return Response(response_message(e.message))
        return Response(response_success(model))
    
    @action(methods=['post'], detail=False)
    def generate_poster(self, request):
        params = getRequestParams(request)
        obj_id = params.get('obj_id')
        
        if not obj_id:
            return Response({'code': 400, 'message': "obj_id 参数必填"})

        # 获取 SKU 商品
        item = ItemDao().findOneByObjId(obj_id)
        skus = item.item_sku.all().order_by('sellingPrice')
        sku = skus.first()
        if not sku:
            return Response({'code': 404, 'message': "SKU 不存在"})

        item_name = sku.item.name
        item_cover_url = sku.coverUrl  # 网络图片地址
        base_img = ''
        try:
            # 加载网络图片
            response = requests.get(item_cover_url, timeout=10)
            if response.status_code == 200:
                base_img = Image.open(BytesIO(response.content)).convert('RGB')  # 统一转为 RGB
            else:
                raise Exception(f"无法加载图片: {item_cover_url}，状态码：{response.status_code}")
        except Exception as e:
            return Response({'code': 500, 'message': str(e)})
        base_img = base_img.resize((300, 300))

        # 创建二维码
        qr = qrcode.QRCode(version=1, box_size=10, border=2)
        qr.add_data(f"https://yourdomain.com/item/{sku.id}")  # 替换为你自己的链接
        qr_img = qr.make_image(fill_color="black", back_color="white").convert('RGB').resize((80, 80))

        # 创建空白画布（白色背景）
        poster = Image.new('RGB', (400, 600), (255, 255, 255))  # 使用 RGB 模式
        draw = ImageDraw.Draw(poster)

        # 粘贴商品图
        poster.paste(base_img, (50, 50))  # 不再使用 mask，因为是 RGB

        # 粘贴二维码
        poster.paste(qr_img, (280, 450))

        # 添加文字（商品名称）
        try:
            font = ImageFont.truetype(os.path.join(BASE_DIR, 'apps/common/font/Open Sans Regular 400.ttf'), 36)  # 使用系统中的Arial字体，大小为36
        except IOError:
            font = ImageFont.load_default()  # 如果Arial字体不可用，则使用默认字体

        draw.text((50, 400), f"商品：{item_name}", fill=(0, 0, 0), font=font)

        # 保存到内存
        img_io = BytesIO()
        # 保存图片
        poster.save(img_io, 'PNG')
        # 从BytesIO中获取图片数据
        img_byte = img_io.getvalue()
        # 将图片转换为base64格式
        img_base64 = base64.b64encode(img_byte)
        # 将base64编码转换为字符串
        img_base64_str = img_base64.decode('utf-8')

        print('img_base64_str', img_base64_str)
        return Response(response_success({'img_base64_str': img_base64_str}))
    
    @action(methods=['post'], detail=False)
    def getItemsByIds(self, request):
        params = getRequestParams(self.request)
        ids = params.get('ids')
        if type(ids) != list:
            return Response(response_message('ids参数格式错误'))
        _list = ItemDao().findAllItemForC().filter(id__in=ids)
        return Response(response_success({'list': ItemModelSerializer(_list, many=True, context={'request':request}).data}))
